package cyce.common;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.StringReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

/**
 * This class is used to read XML configuration 
 * @author CYCE
 */
public class ConfigParser {
	private Map<String, String> configValues = new HashMap<String, String>();
	
	@SuppressWarnings("unchecked")
	public ConfigParser(String path) throws Exception{
		
		try{
			String xml = "";
			BufferedReader reader = new BufferedReader(new FileReader(path));
			String line = reader.readLine();
			while (line != null) {
				xml += line;
				line = reader.readLine();
			}
			
			SAXBuilder builder = new SAXBuilder();
			Document doc = builder.build(new StringReader(xml));
			
			Element root = doc.getRootElement();
			
			List<Element> keys = root.getChildren("setting");
			
			for (Element key : keys){
				configValues.put(
						key.getAttributeValue("name"),
						key.getText());
			}
		}catch (Exception e){
			throw new Exception("Could not read setings", e);
		}
	}
	
	/**
	 * Get the configuration value specified by the given key
	 * @param key The identifier of the config value
	 * @return The config value itself
	 */
	public String getValue(String key){
		return configValues.get(key);
	}
}
